package com.huan.drools;

import lombok.extern.slf4j.Slf4j;
import org.kie.api.KieBase;
import org.kie.api.conf.EqualityBehaviorOption;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.kie.internal.utils.KieHelper;

/**
 * drools 测试类
 */
@Slf4j
public class DroolsStringOrFileRuleApplication {


    public static void main(String[] args) {
        // 从文件中加载规则文件
        loadRuleFromFile();
        // 从字符串中加载规则文件
        loadRuleFromString();
    }

    private static void loadRuleFromFile() {
        KieHelper kieHelper = new KieHelper();
        Resource resource = ResourceFactory.newClassPathResource("rules/alway-rule.drl", "UTF-8");
        kieHelper.addResource(resource, ResourceType.DRL);
        KieBase kieBase = kieHelper.build();
        KieSession kieSession = kieBase.newKieSession();
        kieSession.fireAllRules();
        kieSession.dispose();
    }

    private static void loadRuleFromString() {
        String drl = "package rules\n" +
                "\n" +
                "rule \"rule-01\"\n" +
                "    when\n" +
                "        $i: Integer()\n" +
                "    then \n" +
                "        System.out.println(\"规则:[\"+drools.getRule().getName()+\"]执行,规则内存中存在的值是:\"+$i);\n" +
                "end";


        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(drl, ResourceType.DRL);
        // 创建KieBase是一个成本很大的
        KieBase kieBase = kieHelper.build(EqualityBehaviorOption.IDENTITY);
        log.info("{}", kieBase);
        // 创建KieSession成本小

        KieSession kieSession = kieBase.newKieSession();

        kieSession.insert(123);
        kieSession.fireAllRules();

        kieBase.removeRule("rules", "rule-01");

        kieSession.insert(456);
        kieSession.fireAllRules();

        kieSession.dispose();
    }
}
